<?php
global $db;
require_once "../../tool/sql.php";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
session_start();
$data = $_POST["data"];
if(strlen($data) < 3) {
    die("Data Error");
}
$data = json_decode($data,true);

$res = $db->selectById("userinfo","learned_word_count","name",$_SESSION['user']);
if($res == null)
    die($db->getStmtError());
$learned_count = 0;
foreach ($res as $r) {
    $learned_count = $r['learned_word_count'];
}
$page = (int)($learned_count / 100);
$now_page_count = $learned_count % 100;
$learned_count += count($data);  //这里留下了一个bug，如果单词出现重复，将会造成
if(!$db->update("userinfo","name='".$_SESSION['user']."'",["learned_word_count"=>$learned_count]))
    echo $db->getStmtError();
$new_wdl = [];
foreach ($data as $k => $value) {
    $new_wdl[$k] = [$value,0,0,1200];
    if (isset($_POST["public_cache_map"])) {
        $new_wdl[$k][2] = json_decode($_POST["public_cache_map"],true)[$k];
    }
    //  ["context"=>{value},"last-time"=>{time},"last-mis-count"=>{count},"S"=>{S}],
}
$where = "`list_id` = $page and `owner_name` = '".$_SESSION['user']."'";
$res = $db->select("wordlist","text",$where);
if($res == null)
    die("Wordlist Not Found");
$old_wdl = json_decode($res[0]['text'],true);
$old_wdl == null && ($old_wdl = array());

function array_append($old,$new) {
    foreach ($new as $k=>$v) {
        if(!isset($old[$k])) {
            $old[$k] = $v;
        } else {
            $old[$k."(new)"] = $v;
        }
    }
    return $old;
}

if($now_page_count + count($data) > 100) {
    $new_wdl_former = array_slice($new_wdl,0,100-$now_page_count);
    $new_wdl_latter = array_slice($new_wdl,100-$now_page_count);
    $new_wdl = array_append($old_wdl,$new_wdl_former);
    if(!$db->update('wordlist',$where,["text"=>json_encode($new_wdl)]))
        die($db->getError());
    if(!$db->insert('wordlist',["owner_name"=>$_SESSION['user'],"list_id"=>$page+1,"text"=>json_encode($new_wdl_latter)]))
        die($db->getStmtError());
}else{
    $new_wdl = array_append($old_wdl,$new_wdl);
    if(!$db->update('wordlist',$where,["text"=>json_encode($new_wdl)]))
        die($db->getStmtError());
}
echo "0";

